﻿namespace Token.Module;

public class AutomaticInjection
{
    public static void InjectionService(IServiceCollection services, IEnumerable<Type> types)
    {
        // 扫描所有需要注入的程序集（只有引用的模块）。并且去重，只扫描继承了ITokenModule的程序集
        foreach (var type in types.Select(x => x.Assembly).Distinct()
                     .SelectMany(x => x.GetTypes().Where(x => x.IsAssignableModule())))
        {
            // 得到继承的接口。
            var interfaces = type.GetDependencyType();

            // 根据继承的接口注入相对应的生命周期。
            if (type.IsAssignableFrom<ITransientDependency>())
            {
                if (interfaces == null)
                {
                    services.AddTransient(type);
                }
                else
                {
                    services.AddTransient(interfaces, type);
                }
            }
            else if (type.IsAssignableFrom<IScopedDependency>())
            {
                if (interfaces == null)
                {
                    services.AddScoped(type);
                }
                else
                {
                    services.AddScoped(interfaces, type);
                }
            }
            else if (type.IsAssignableFrom<ISingletonDependency>())
            {
                if (interfaces == null)
                {
                    services.AddSingleton(type);
                }
                else
                {
                    services.AddSingleton(interfaces, type);
                }
            }
        }
    }
}